/**
 * Copyright (c) 2013-2022 Nikita Koksharov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.command.CommandAsyncExecutor;

/**
 * 读写锁
 */
public class RedissonReadWriteLock extends RedissonExpirable implements RReadWriteLock {

    /**
     * 读写锁的特性
     * 1、 读读兼容、读写互斥、写写互斥、写读互斥
     * 2、 锁可以降级(当线程先获取到写锁，然后再去获取读锁，接着再释放写锁)，但不能升级(先获取读锁，然后再获取写锁，再释放读锁）
     */
    public RedissonReadWriteLock(CommandAsyncExecutor commandExecutor, String name) {
        super(commandExecutor, name);
    }

    /**
     * 为什么只有锁降级，没有锁升级
     * 1、锁降级指 同一线程先获取写锁，然后再获取读锁，这样可以保证数据的一致性和正确性，在一定程度上减少了锁的竞争和消耗。
     * 2、锁降级的过程是安全的，因为在获取锁之前，已经获取了写锁，保证了共享资源的独占性和一致性
     * 3、锁升级指 先获取读锁，然后在获取写锁，这样会导致死锁和数据不一致问题。
     * 4、因为在多个线程同时持有读锁的情况下，如果有一个线程尝试获取写锁，则会阻塞其他读锁和写锁，导致死锁
     * 5、在多个线程同时持有读锁的情况下，不能保证共享资源的一致性和正确性，因为读锁允许多个线程共享资源
     * 而写锁需要独占贡献资源，这两个操作不兼容
     */

    @Override
    public RLock readLock() {
        return new RedissonReadLock(commandExecutor, getName());
    }

    @Override
    public RLock writeLock() {
        return new RedissonWriteLock(commandExecutor, getName());
    }




}
